const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
const router = new Router()
const BlogModel = require('../models/blog')
const TagModel = require('../models/tag')
const showdown = require('showdown')
const middleware = require('./middleware')

// 获取所有博客列表
router.get('/listOfAll', async (ctx, next) => {
  ctx.used = true
  ctx.body = await BlogModel.getAllList()
  return next()
})

// 获取展示用博客列表
router.get('/listOfDisplay', async (ctx, next) => {
  ctx.used = true  
  ctx.body = await BlogModel.getDisplayList(ctx.query.page)
  return next()
})

// 根据博客href查询博客id
router.get('/href/:href', async (ctx, next) => {
  ctx.used = true  
  ctx.body = await BlogModel.getBlogByHref(ctx.params.href)
  if(!ctx.body) throw new Error('查无此文!')
  return next()
})

// 获取博客详情
router.get('/:id', async (ctx, next) => {
  if(!ctx.used) {
    if(middleware.examineId(ctx.params.id)) throw new Error('传入博客id有误!')
    let detail = await BlogModel.getContent(ctx.params.id)
    const converter = new showdown.Converter()
    const htmlContent = converter.makeHtml(detail.content)
    // 不能直接...detail 这样展开的detail还包括一大堆别的东西…
    detail = {
      tag: detail.tag,
      _id: detail._id,
      title: detail.title,
      content: detail.content,
      time: detail.time,
      href: detail.href,
      htmlContent
    }
    ctx.body = detail
  }
  return next()
})

// 新建博客
router.post('/', async(ctx, next) => {
  ctx.body = await BlogModel.add(ctx.request.body)
  return next()
})

// 删除博客
router.delete('/:id', async(ctx, next) => {
  await BlogModel.delete(ctx.params.id)
  ctx.body = {success: true}  
  return next()
})

// 查找博客
router.get('/findByTitle', async(ctx, next) => {
  ctx.used = true
  ctx.body = await BlogModel.findByTitle(ctx.query.search)
  return next()
})

// 给博客添加标签
router.post('/tag/:id', async(ctx, next) => {
  if(!ctx.used) {
    const tagId = ctx.request.body.tagId
    const blogId = ctx.params.id
    if(middleware.examineId(tagId)) throw new Error('传入标签id有误!')
    if(middleware.examineId(blogId)) throw new Error('传入博客id有误!')
    await BlogModel.addTag(blogId, tagId)
    ctx.body = await TagModel.getTagById(tagId)    
  }
  ctx.used = true  
  return next()
})

// 给博客移除标签
router.delete('/tag/:id', async(ctx, next) => {
  if(!ctx.used) {
    const tagId = ctx.request.body.tagId
    const blogId = ctx.params.id
    if(middleware.examineId(tagId)) throw new Error('传入标签id有误!')
    if(middleware.examineId(blogId)) throw new Error('传入博客id有误!')
    await BlogModel.removeTag(blogId, tagId)
  }
  ctx.used = true
  return next()
})

// 更新博客
router.put('/:id', async(ctx, next) => {
  if(!ctx.used) {
    await BlogModel.update(ctx.params.id, ctx.request.body)
    ctx.body = {success: true}
  }
  return next()
})

module.exports = router